/* 
   Author: dependence team
*/
DPND = {
   common: {
      init: function(){
				$('.feedEntries .feedBody a').attr('target', '_blank');
         
				 // expand/collapse folders by clicking the folder itself, not the title
         $('.feedfolderLink .icon').click(function(e) {
            var $this = $(this).parent('.feedfolderLink'),
                $feeds = $this.siblings('.subscriptionFolder'),
                $icon = $this.children('.icon');
             
            $feeds.toggleClass('open').slideToggle(250, function() {
               $icon.toggleClass('icon-folder').toggleClass('icon-folder-open');
            });
						
						e.preventDefault();
         });
				 
				 $('.feedfolderLink').click(function(e) {
					 // TO-DO: view entries by folder (this needs to be implemented in the backend still)
				 });
				 
				 
				 
				 // TO-DO: This needs to be made to suck less.  Probably need to make an API controller?
				$('.feedEntry').live('click', function() {
					var id = $(this).attr('id').split('-')[1];
					$.post('/entries/mark_read/' + id, null, function(data, stat, xhr) {
						//updateFeeds();
					});
				});
				
				
				
				$(window).scroll(function(e) {
					var $to_focus = false;
					var $entries = $('#entries .feedEntry');
					var cnt = 0;
					$entries.each(function(idx, val) {
						var $ent = $(val);
						var pos = $ent.offset().top  - $(window).scrollTop();
						if (pos < 100) {
							$to_focus = $ent;
						}
						cnt++;
						if (cnt >= $entries.length) {
							$entries.removeClass('focus');
							if ($to_focus !== false) {
								$to_focus.addClass('focus');
								// TO-DO: Actually mark it as read here
							}
						}
					});
				});
				
				// More ugliness, but hey, it works for now
				var update_pending = false;
				
				var updateFeeds = function() {
					if (update_pending) { return; }
				  update_pending = true;
					$.post('/feeds/status', null, function(data, stat, xhr) {
						
						// TO-DO: We should cache the results and only flash updates for those feeds that have different counts
						
						var ffs = {};
						
						$('.unreadCount').hide();
						
						if (data && data.result) {
							for (var i = 0; i <=  data.result.length; i++) {
								var feed = data.result[i];
								if (feed && feed.id && feed.unread) {
									
									ffs[feed.feedfolder_id] = ffs[feed.feedfolder_id] ? ffs[feed.feedfolder_id] + parseInt(feed.unread) : parseInt(feed.unread); 
									$feedLink = $('#feedLink-' + feed.id);
									$feedLink.find(' .unreadCount').html(feed.unread).show();
									var originalBg = '#F5F5F5'; // TO-DO: get this dynamically?
									$feedLink.stop().css({backgroundColor: '#FFFF9C'}).animate({backgroundColor: originalBg}, 1500);
								}
							}
						}
						
						// folder totals
						for (var prop in ffs) {
							if (ffs.hasOwnProperty(prop)) {
								$('#feedfolder-' + prop + ' > .unreadCount').html('(' + ffs[prop] + ')').show().css({backgroundColor: '#FFFF9C'}).animate({backgroundColor: originalBg}, 1500);;
							}
						}
						
						update_pending = false;
					}, 'json');
				} // updateFeeds()
				
				updateFeeds();
				
				var feed_update_interval = setInterval(updateFeeds, 5 * 60 * 1000); // poll every 5 minutes
				
				// TO-DO: Wire this thing up (backend work still needed)
				$('#addSubscription').click(function() {
					$form = $('.subscribe');
					if ($form.is(':visible')) {
					  $form.hide(250);	
					} else {
						$form.show(250);	
					}
				});
				
				// TO-DO: wire this thing up
				$('#markAsRead').click(function() {
					//$.post('/feeds/mark_read/all', null, function(data) {
					//	
					//});
				});
				
				$('li.feed a').click(function(e) {
					var url = $(this).attr('href') + '/json';
					var $entry_list = $('#entries ul.feedEntries');
					// TO-DO: add a spinner/loader widget?
					
					$.post(url, null, function(data, stat, xhr) {
						var feed_html = '';
						if (data.entries && data.entries.length > 0) {
							$entry_list.empty();
							
							$('.feedTitle a').attr('href', data.feed.html).html(data.feed.title);
							
							for (var i = 0; i < Math.min(data.entries.length, 30); i++) {
								ent = data.entries[i];
								ent.pub_date = dateFormat(parseInt(ent.pub_date) * 1000, "dddd, mmmm dS, yyyy, h:MM:ss TT");
								feed_html = tmpl("tmpl_feedEntry", ent);
								$entry_list.append(feed_html);
							}
						}
					});
					
					e.preventDefault();
				});
				
				
				
				
	   },
	   finalize: function(){
	      // keyboard shortcuts FTW
	      $(document).keypress(function(e) {
	         var key = e.keydown || e.which,
	             $source = $(e.target);
	             
	         log((new Error).lineNumber, 'key: ' + key, $source);
	         
	         if ($source.is('html')) {
	            switch(key) {
	               case 97: // a
                     break;
                  case 98: // b
                     break;
                  case 99: // c
                     break;
                  case 100: // d
                     break;
                  case 101: // e
                     break;
                  case 102: // f
                     $('div.sideBarNav').toggle(0, function() {
                        if ($(this).is(':visible')) {
                           $('div.mainContent').css({'margin-left': '290px'});      
                        } else {
                           $('div.mainContent').css({'margin-left': '0'});      
                        }
                     });
                     
                     break;
                  case 103: // g
                     break;
                  case 104: // h
                     break;
                  case 105: // i
                     break;
                  case 106: // j
                     break;
                  case 107: // k
                     break;
                  case 108: // l
                     break;
                  case 109: // m
                     break;
                  case 110: // n
                     break;
                  case 111: // o
                     break;
                  case 112: // p
                     break;
                  case 113: // q
                     break;
                  case 114: // r
                     break;
                  case 115: // s
                     break;
                  case 116: // t
                     break;
                  case 117: // u
                     break;
                  case 118: // v
                     break;
                  case 119: // w
                     $('header.topbar').toggle();
                     break;
                  case 120: // x
                     break;
                  case 121: // y
                     break;
                  case 122: // z
                     break;
	            }
	         }
	      })
	   }	
   }
}
UTIL = {
	fire : function(func,funcname, args){
		var namespace = DPND;  // indicate your obj literal namespace here
		funcname = (funcname === undefined) ? 'init' : funcname;
		if (func !== '' && namespace[func] && typeof namespace[func][funcname] == 'function'){
			namespace[func][funcname](args);
		} 
	}, 
	loadEvents : function(){
		var bodyId = document.body.id;
		// hit up common first.
		UTIL.fire('common');
		// do all the classes too.
		$.each(document.body.className.split(/\s+/),function(i,classnm){
			UTIL.fire(classnm);
			UTIL.fire(classnm,bodyId);
		});
		UTIL.fire('common','finalize');
	} 
}; 
// kick it all off here 
$(document).ready(UTIL.loadEvents);
